# coding:utf-8
import pycurl,time,StringIO,sys,re,os
import inspect
#公用
c=inspect.currentframe()
namefilepath = os.path.dirname(c.f_code.co_filename)

class ProxyVaild(object):
    crl = None
    headinfo = StringIO.StringIO()
    bodyinfo =  StringIO.StringIO()
    ip_port = None
    timeout_ms = 60000
    ProxyTypeDict = {'HTTP':pycurl.PROXYTYPE_HTTP,'SOCKS4':pycurl.PROXYTYPE_SOCKS4,'SOCKS5':pycurl.PROXYTYPE_SOCKS5}
    ProxyType = pycurl.PROXYTYPE_HTTP
    url = 'http://www.google.com'
    Body = False
    geoip = None
    proxylevel = {'TRANSPARENT_PROXY':'0','ANONYMOUS':'1','HIGH_ANONYMITY':'2'}
    def __init__(self):
        self.crl = pycurl.Curl()
    def SetBody(self,Body = False):
        self.Body = Body
    def SetCallBackVaildUrl(self,url):
        self.url = url
    def SetProxy(self,ip_port):
        self.ip_port = ip_port
    def SetProxyType(self,ProxyType):
        self.ProxyType = ProxyType
    def SetTimeOut(self,timeout_ms):
        self.timeout_ms = timeout_ms
    def SetGeoIp(self,geoip):
        self.geoip = geoip
    def __SetNn(self):
        self.crl.setopt(pycurl.FOLLOWLOCATION, 1)
        #self.crl.setopt(pycurl.VERBOSE,1)  #输出debug信息
        self.crl.setopt(pycurl.USERAGENT,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36')
        self.crl.setopt(pycurl.HEADERFUNCTION, self.headinfo.write)
        self.crl.setopt(pycurl.URL, self.url)
        if self.ip_port is not None:
            self.crl.setopt(pycurl.PROXY, "%s"%self.ip_port)
        self.crl.setopt(pycurl.TIMEOUT_MS,self.timeout_ms)
        if self.ProxyTypeDict.has_key(self.ProxyType):
            self.crl.setopt(pycurl.PROXYTYPE, self.ProxyTypeDict[self.ProxyType])
        else:
            self.crl.setopt(pycurl.PROXYTYPE, self.ProxyTypeDict['HTTP'])
        if self.Body is False:
            self.crl.setopt(pycurl.NOBODY,1)
        else:
            self.crl.setopt(pycurl.WRITEFUNCTION, self.bodyinfo.write)
    def Run(self):
        self.__SetNn()
        ReturnValue = []
        try:
            p = re.compile(r'Result=\S+',re.DOTALL)
            s = time.time()
            ret = self.crl.perform()

            #print self.bodyinfo.getvalue()
            #ReturnValue.append( self.crl.getinfo(pycurl.HTTP_CODE) )
            #ReturnValue.append( self.headinfo.getvalue() )
            #ReturnValue.append( self.bodyinfo.getvalue() )
            '''
            取消减少内存占用
            '''
            ReturnValue.append(self.ip_port)
            ReturnValue.append(self.ProxyType)
            level = p.search(self.bodyinfo.getvalue()).group()
            if level:
                level1 = level.split('=')[1]
            else:
                level1 = 'TRANSPARENT_PROXY'
            ReturnValue.append(self.proxylevel[ level1 ])

            response = self.geoip.city(self.ip_port.split(':')[0])
            ReturnValue.append(response.country.iso_code)
            ReturnValue.append(0)
            ReturnValue.append(time.strftime("%Y-%m-%d %H:%M:%S"))
            ReturnValue.append(response.country.iso_code)

            ReturnValue.append( time.time()-s ) #响应时间
            ReturnValue.append(time.time()) #创建时间
            ReturnValue.append(0) #更新时间
            # response.country.name
            # response.city.name

            '''
            可能在这里进行分类
123.138.59.204|80|HTTP|2|CN|0|2014-05-13 19:17:46|CN
            '''
        except Exception, e:
            pass
            #traceback.print_exc()
        finally:
            #self.headinfo.close() #多线程下错误
            #self.bodyinfo.close() #多线程下错误
            self.crl.close()
        return ReturnValue

def echo(msg,infoleve = 'info'):
    '''
    warnning
    info
    error
    '''
    fp = open('./log/%s.log'%(time.strftime("%Y-%m-%d")),'a+')
    fp.write( '[%s]  %s -callback: %s line: %s .  %s %s'%(infoleve,msg ,sys._getframe().f_back.f_code.co_name,
                                                          sys._getframe().f_back.f_lineno,time.strftime("%Y-%m-%d %H:%M:%S"), "\t\n"))
    fp.close()
#print proxycheckone('27.115.18.18:8080')
#print proxycheckone('1.85.17.82:1080')
#url = "http://www.google.com"


'''
a = ProxyVaild()
a.SetProxy('192.168.1.66:8183')
a.SetProxyType('HTTP')
a.SetCallBackVaildUrl('http://192.168.1.68/proxyheader.php')
a.SetBody(True)
print a.Run()
'''
